package com.pai4j.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class UrlUtil {

    /**
     * 构建带查询参数的URL
     * @param api 基础API地址
     * @param params 参数Map
     * @return 完整URL字符串
     */
    public static String buildUrl(String api, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return api;
        }

        StringBuilder queryString = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (queryString.length() > 0) {
                    queryString.append("&");
                }
                String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
                String encodedValue = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
                queryString.append(encodedKey)
                          .append("=")
                          .append(encodedValue);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("URL encoding failed", e);
        }

        return api + (api.contains("?") ? "&" : "?") + queryString;
    }
}